<template>
  <div class="departments">
    <!-- 卡片内容 -->
    <el-card class="box-card">
      <!-- tabs -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织结构" name="first" />
        <!-- layout 栅格(shan ge)布局 -->
        <el-row type="flex" justify="space-between">
          <el-col :span="6">
            <h4>我爱敲代码 冲冲冲！！！</h4>
          </el-col>
          <el-col class="right-col" :span="6">
            <span class="leader">负责人</span>
            <!-- 下拉菜单 -->
            <el-dropdown>
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <!-- 点击 添加顶级节点 -->
                  <el-button
                    type="text"
                    @click="dialogFormVisible = true"
                  >添加子部门</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
        <!-- 和底部的内容分割开来 -->
        <el-divider />
        <!-- tree -->
        <el-tree
          :data="departs"
          :props="defaultProps"
          @node-click="handleNodeClick"
        >
          <!-- 通过插槽自定义结构 -->
          <template #default="{ data }">
            <el-row type="flex" justify="space-between">
              <el-col :span="6">{{ data.name }}</el-col>
              <el-col :span="6" class="right-col">
                <span class="leader">{{ data.manager }}</span>
                <!-- 下拉菜单 -->
                <el-dropdown>
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <el-button
                        type="text"
                        @click="addChildren(data)"
                      >添加子部门</el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button
                        type="text"
                        @click="enterEdit(data)"
                      >查看部门</el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button
                        type="text"
                        @click="delDep(data)"
                      >删除部门</el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-tabs>
    </el-card>

    <!-- <el-button
      type="text"
      @click="dialogFormVisible = true"
    >打开嵌套表单的 Dialog</el-button> -->

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @closed="closed"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          :label-width="formLabelWidth"
          prop="code"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          :label-width="formLabelWidth"
          prop="manager"
        >
          <el-select
            v-model="form.manager"
            placeholder="请选择"
            @focus="onFocus"
          >
            <el-option
              v-for="item in managers"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          :label-width="formLabelWidth"
          prop="introduce"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// list:数组
// pid:确定顶级节点
function formData(list, pid) {
  return list.filter((v) => {
    if (v.pid === pid) {
      v.children = formData(list, v.id)
      // v.children=list.filter(vc=>{
      //   if(vc.pid===v.id){
      //     return true
      //   }
      // })
      return true
    }else{
      return false
    }
  })
}
import {
  getDepartments,
  addDepartments,
  getDepartmentById,
  editDepartment,
  delDepartments
} from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'Departments',
  data() {
    return {
      managers: [],
      // dialog里的表单
      // 是否显示弹框
      dialogFormVisible: false,
      formLabelWidth: '100px',
      // form里面的数据
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      activeName: 'first',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ],
      // 表单校验规则
      rules: {
        code: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请填写1-50个字符', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '请填写1-50个字符', trigger: 'change' }
        ],
        manager: [{ required: true, message: '不能为空', trigger: 'blur' }],
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请填写1-50个字符', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // dialog关闭时的回调函数
    closed() {
      this.form = {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门id
      }
    },
    // 删除部门
    delDep(data) {
      this.$confirm('是否要删除部门？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delDepartments(data.id)
          this.getData()
          this.$message({
            type: 'success',
            message: '删除部门成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 新增子部门
    addChildren(data) {
      // console.log(data);
      // 把点击的父节点的id赋值给子节点的pid
      this.form.pid = data.id
      // 弹框
      this.dialogFormVisible = true
    },
    // 清空表单
    onCancel() {
      this.form = {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '', // 部门名称
        pid: '' // 父级部门id
      }
      // 关闭弹框
      this.dialogFormVisible = false
    },
    // 进入编辑
    async enterEdit(data) {
      // 查看部门信息接口
      const res = await getDepartmentById(data.id)
      this.form = { ...res }
      // 弹框
      this.dialogFormVisible = true
    },
    handleNodeClick() {},
    async onFocus() {
      const res = await getEmployeeSimple()
      this.managers = res
    },
    // 获取tree数据的方法
    async getData() {
      const res = await getDepartments()
      this.departs = formData(res.depts, '')
      // const res1 = res.depts.filter((v) => {
      //   if (v.pid === '-1') {
      //     return false
      //   }
      // })
      // const res2 = res1.filter((v) => {
      //   if (v.pid === '') {
      //     return true
      //   }
      // })
      // res2.forEach((v) => {
      //   v.children = res1.filter((dv) => {
      //     if (v.id === dv.pid) {
      //       return true
      //     }
      //   })
      // })
      // this.departs = res2
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          if (this.form.id) {
            // 走编辑
            const res = await editDepartment(this.form)
          } else {
            // 走添加
            // 添加部门
            const res = await addDepartments(this.form)
          }
          this.$message.success(`${this.title}成功`)
          // this.dialogFormVisible = false
          // 调用清空表单的逻辑
          this.onCancel()
          // 新增成功后再调用获取数据的方法，把新增的数据加载到页面上
          this.getData()
        } else {
          this.$message.error('数据格式有误,请检查哦!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.departments {
  .el-tabs__content {
    padding: 20px 40px 40px;
  }
  h4 {
    margin: 0;
    color: #666;
  }
  .leader {
    font-size: 14px;
    margin-right: 10px;
  }
  .box-card {
    width: 100%;
    .el-row {
      .right-col {
        text-align: right;
      }
    }
  }
  .box-card.el-card.is-always-shadow {
    box-shadow: 0 2px 12px 0 #f5cace;
  }
  .el-tree {
    .el-row {
      flex: 1;
      .right-col {
        text-align: right;
      }
    }
  }
}
</style>
